<?php
/**
 * 购买
 *
 * @好商城 (c) 2015-2018 33HAO Inc. (http://www.33hao.com)
 * @license    http://www.33 hao.c om
 * @link       交流群号：138182377
 * @since      好商城提供技术支持 授权请购买shopnc授权
 */



defined('In33hao') or exit('Access Invalid!');

class member_buyControl extends mobileMemberControl {

    public function __construct() {
        parent::__construct();
    }

    /**
     * 购物车、直接购买第一步:选择收获地址和配置方式
     */
    public function buy_step1Op() {
        $cart_id = explode(',', $_POST['cart_id']);
        $logic_buy = logic('buy');

        //得到会员等级
        $model_member = Model('member');
        $member_info = $model_member->getMemberInfoByID($this->member_info['member_id']);
        if ($member_info){
            $member_gradeinfo = $model_member->getOneMemberGrade(intval($member_info['member_exppoints']));
            $member_discount = $member_gradeinfo['orderdiscount'];
            $member_level = $member_gradeinfo['level'];
        } else {
            $member_discount = $member_level = 0;
        }
        if($_POST['is_point']){
            // 得到积分商品数据
            $result = $logic_buy->buySetpPoint($cart_id,$_POST['ifcart'], $this->member_info['member_id'], $this->member_info['store_id'], null, $member_discount, $member_level);
        }else {
            //得到购买数据
            $result = $logic_buy->buyStep1($cart_id, $_POST['ifcart'], $this->member_info['member_id'], $this->member_info['store_id'], null, $member_discount, $member_level);
        }
        if(!$result['state']) {
            output_error($result['msg']);
        } else {
            $result = $result['data'];
        }
        if (intval($_POST['address_id']) > 0) {
            $result['address_info'] = Model('address')->getDefaultAddressInfo(array('address_id'=>intval($_POST['address_id']),'member_id'=>$this->member_info['member_id']));
        }
        if ($result['address_info']) {
            $data_area = $logic_buy->changeAddr($result['freight_list'], $result['address_info']['city_id'], $result['address_info']['area_id'], $this->member_info['member_id']);
            if(!empty($data_area) && $data_area['state'] == 'success' ) {
                if (is_array($data_area['content'])) {
                    foreach ($data_area['content'] as $store_id => $value) {
                        $data_area['content'][$store_id] = ncPriceFormat($value);
                    }
                }
            } else {
                output_error('地区请求失败');
            }
        }
        $model_setting = Model('setting');
        $list_setting = $model_setting->getListSetting();
        //积分商品抵扣
        $use_point = 0;
        //整理数据
        $store_cart_list = array();
        $store_total_list = $result['store_goods_total_1'];
        foreach ($result['store_cart_list'] as $key => $value) {
            if (is_array($value) && !empty($value[0])) {
                foreach($value as $v){
                    if ($v['shop_cate_value']) {
                        $use_point += $v['shop_cate_value'] * $v['goods_num']*$list_setting['points_dikou'];
                    }
                }
            }
            $store_cart_list[$key]['goods_list'] = $value;
            $store_cart_list[$key]['store_goods_total'] = $result['store_goods_total'][$key];

            $store_cart_list[$key]['store_mansong_rule_list'] = $result['store_mansong_rule_list'][$key];

            if (is_array($result['store_voucher_list'][$key]) && count($result['store_voucher_list'][$key]) > 0) {
                reset($result['store_voucher_list'][$key]);
                $store_cart_list[$key]['store_voucher_info'] = current($result['store_voucher_list'][$key]);
                $store_cart_list[$key]['store_voucher_info']['voucher_price'] = ncPriceFormat($store_cart_list[$key]['store_voucher_info']['voucher_price']);
                $store_total_list[$key] -= $store_cart_list[$key]['store_voucher_info']['voucher_price'];
            } else {
                $store_cart_list[$key]['store_voucher_info'] = array();
            }

            $store_cart_list[$key]['store_voucher_list'] = $result['store_voucher_list'][$key];
            if(!empty($result['cancel_calc_sid_list'][$key])) {
                $store_cart_list[$key]['freight'] = '0';
                $store_cart_list[$key]['freight_message'] = $result['cancel_calc_sid_list'][$key]['desc'];
            } else {
                $store_cart_list[$key]['freight'] = '1';
            }
            $store_cart_list[$key]['store_name'] = $value[0]['store_name'];
        }

        $buy_list = array();

        $buy_list['freight_hash'] = $result['freight_list'];
        $buy_list['address_info'] = $result['address_info'];
        $buy_list['ifshow_offpay'] = $result['ifshow_offpay'];
        $buy_list['vat_hash'] = $result['vat_hash'];
        $buy_list['inv_info'] = $result['inv_info'];
        $buy_list['available_predeposit'] = $result['available_predeposit'];
        $buy_list['available_rc_balance'] = $result['available_rc_balance'];
        if (is_array($result['rpt_list']) && !empty($result['rpt_list'])) {
            foreach ($result['rpt_list'] as $k => $v) {
                unset($result['rpt_list'][$k]['rpacket_id']);
                unset($result['rpt_list'][$k]['rpacket_end_date']);
                unset($result['rpt_list'][$k]['rpacket_owner_id']);
                unset($result['rpt_list'][$k]['rpacket_code']);
            }
        }
        $buy_list['rpt_list'] = $result['rpt_list'] ? $result['rpt_list'] : array();
        $buy_list['zk_list'] = $result['zk_list'];

        if ($data_area['content']) {
            $store_total_list = Logic('buy_1')->reCalcGoodsTotal($store_total_list,$data_area['content'],'freight');
            //返回可用平台红包
            $result['rpt_list'] = Logic('buy_1')->getStoreAvailableRptList($this->member_info['member_id'],array_sum($store_total_list),'rpacket_limit desc');
            reset($result['rpt_list']);
            if (is_array($result['rpt_list']) && count($result['rpt_list']) > 0) {
                $result['rpt_info'] = current($result['rpt_list']);
                unset($result['rpt_info']['rpacket_id']);
                unset($result['rpt_info']['rpacket_end_date']);
                unset($result['rpt_info']['rpacket_owner_id']);
                unset($result['rpt_info']['rpacket_code']);
            }
        }
        $buy_list['order_amount'] = ncPriceFormat(array_sum($store_total_list)-$result['rpt_info']['rpacket_price']);
        $buy_list['rpt_info'] = $result['rpt_info'] ? $result['rpt_info'] : array();
        $buy_list['address_api'] = $data_area ? $data_area : '';

        foreach ($store_total_list as $store_id => $value) {
            $store_total_list[$store_id] = ncPriceFormat($value);
        }
        $buy_list['store_final_total_list'] = $store_total_list;
        //积分抵扣具体额度计算
        $buy_list['member_points'] = $member_info['member_points'];
        $can_use_points = $member_info['member_points'] > $use_point ? $use_point : $member_info['member_points'];
        $buy_list['dikou'] = sprintf("%.1f", $can_use_points/$list_setting['points_dikou']);
        $buy_list['use_point'] = $can_use_points;
        //批发折扣
        foreach ($store_cart_list as $k=>$v){
              $percnt = 0; // 每个可节省金额
              $oldprice = ''; //原价格
              $pifaall = '';//批发价
              foreach ($v['goods_list'] as $key => $val){
                  //查询数据表
                    $goodsInfo = Model('goods')->getGoodsInfo(array('goods_id'=>$val['goods_id']));
                    //判断是否可享折扣
                    if($val['goods_num']>=$goodsInfo['buy_num']){
                        //批发可享折扣
                           $pifa = ($val['goods_price']*$val['goods_num'])*($goodsInfo['buy_percent']/100);
                           //折后批发总价
                           $pifaprice = ($val['goods_price']*$val['goods_num'])-$pifa;
                           //将批发折扣数据带出前台
                           $v['goods_list'][$key]['pifa'] = $pifa;
                           //折后批发总价 累加
                           $pifaall  += $pifaprice;
                           //商品原价总和
                           $oldprice += $val['goods_price']*$val['goods_num'];


                    }else{
                        //批发可享折扣
                        $pifa = 0.00;
                        //折后批发总价
                        $pifaprice = ($val['goods_price']*$val['goods_num'])-$pifa;
                        //将批发折扣数据带出前台
                        $v['goods_list'][$key]['pifa'] = $pifa;
                        //折后批发总价 累加
                        $pifaall  += $pifaprice;
                        //商品原价总和
                        $oldprice += $val['goods_price']*$val['goods_num'];
                    }
              }
              //节省金额
              $percnt = $oldprice-$pifaall;
              $store_cart_list[$k] = $v;
              $store_cart_list[$k]['pifaall'] = $pifaall;
              $store_cart_list[$k]['s_pifa_percent'] = $percnt;
        }
        $buy_list['store_cart_list'] = $store_cart_list;
        output_data($buy_list);
    }

    /**
     * 购物车、直接购买第二步:保存订单入库，产生订单号，开始选择支付方式
     *
     */
    public function buy_step2Op() {

        $param = array();
        $param['ifcart'] = $_POST['ifcart'];
        $param['cart_id'] = explode(',', $_POST['cart_id']);
        $param['address_id'] = $_POST['address_id'];
        $param['vat_hash'] = $_POST['vat_hash'];
        $param['offpay_hash'] = $_POST['offpay_hash'];
        $param['offpay_hash_batch'] = $_POST['offpay_hash_batch'];
        $param['pay_name'] = $_POST['pay_name'];
        $param['invoice_id'] = $_POST['invoice_id'];
        $param['rpt'] = $_POST['rpt'];
        $param['my_store_id'] = $_POST['my_store_id'] ? $_POST['my_store_id'] : 0;
        //处理代金券
        $voucher = array();
        $post_voucher = explode(',', $_POST['voucher']);
        if(!empty($post_voucher)) {
            foreach ($post_voucher as $value) {
                list($voucher_t_id, $store_id, $voucher_price) = explode('|', $value);
                $voucher[$store_id] = $value;
            }
        }
        $param['voucher'] = $voucher;

        $_POST['pay_message'] = trim($_POST['pay_message'],',');
        $_POST['pay_message'] = explode(',',$_POST['pay_message']);
        $param['pay_message'] = array();
        if (is_array($_POST['pay_message']) && $_POST['pay_message']) {
            foreach ($_POST['pay_message'] as $v) {
                if (strpos($v, '|') !== false) {
                    $v = explode('|', $v);
                    $param['pay_message'][$v[0]] = $v[1];
                }
            }
        }
        $param['pd_pay'] = $_POST['pd_pay'];
        $param['rcb_pay'] = $_POST['rcb_pay'];
        $param['password'] = $_POST['password'];
        $param['fcode'] = $_POST['fcode'];
        $param['order_from'] = 2;
        $param['use_points'] = intval($_POST['use_points']);
        $logic_buy = logic('buy');

        //得到会员等级
        $model_member = Model('member');
        $member_info = $model_member->getMemberInfoByID($this->member_info['member_id']);

        if ($member_info){
            $member_gradeinfo = $model_member->getOneMemberGrade(intval($member_info['member_exppoints']));
            $member_discount = $member_gradeinfo['orderdiscount'];
            $member_level = $member_gradeinfo['level'];
            if ($param['use_points']) {
                $param['use_points'] = $member_info['member_points'] > $param['use_points'] ? $param['use_points'] : $member_info['member_points'];
            }
        } else {
            $member_discount = $member_level = 0;
        }
        $result = $logic_buy->buyStep2($param, $this->member_info['member_id'], $this->member_info['member_name'], $this->member_info['member_email'],$member_discount,$member_level);
        if(!$result['state']) {
            output_error($result['msg']);
        }
        $order_info = current($result['data']['order_list']);
        output_data(array('pay_sn' => $result['data']['pay_sn'],'payment_code'=>$order_info['payment_code'],'totalPrice'=>$order_info['order_amount']));
    }

    /**
     * 积分购买第二步
     */
    public function buy_Pointstep2Op(){
        $model_pointcart = Model('pointcart');
        $cart = explode("|",$_POST['cart_id']);
        // 获取提交过来的积分数据
        $data = $this->getPointProdInfo($cart);
        if (!$data['state']){

        }
        $pointprod_arr = $data['data'];
        unset($data);
        //验证积分数是否足够
        $data = $model_pointcart->checkPointEnough($pointprod_arr['pgoods_pointall'], $_SESSION['member_id']);
        if (!$data['state']){
            $res = ['status'=>400,'msg'=>$data['msg']];
            output_data($res);
        }
        unset($data);
        //创建兑换订单
        $data = Model('pointorder')->createOrder($_POST, $pointprod_arr, array('member_id'=>$this->member_info['member_id'],'member_name'=>$this->member_info['member_name'],'member_email'=>$this->member_info['member_email']));
        if (!$data['state']){
            $res = ['status'=>400,'msg'=>$data['msg']];
            output_data($res);
        }
        $order_id = $data['data']['order_id'];
        $data['state'] = 200;
        $data['url'] = "index.php?act=member_buy&op=buy_Pointstep3&key=".$_POST['key']."&order_id=".$order_id;
        output_data($data);
    }

    /**
     * 积分购买第二步
     */
    public function buy_Pointstep3Op(){
        $order_id = intval($_GET['order_id']);
        if ($order_id <= 0){
            $res = ['status'=>400,'msg'=>"订单参数错误"];
            output_data($res);
        }
        $where = array();
        $where['point_orderid'] = $order_id;
        $where['point_buyerid'] = $_SESSION['member_id'];
        $order_info = Model('pointorder')->getPointOrderInfo($where);
        if (!$order_info){
            $res = ['status'=>400,'msg'=>"订单参数错误"];
            output_data($res);
        }else{
            $res = ['status'=>200,'msg'=>"积分商品购买成功"];
            output_data($res);
        }
    }


    /**
     * 验证密码
     */
    public function check_passwordOp() {
        if(empty($_POST['password'])) {
            output_error('参数错误');
        }

        $model_member = Model('member');

        $member_info = $model_member->getMemberInfoByID($this->member_info['member_id']);
        if($member_info['member_paypwd'] == md5($_POST['password'])) {
            output_data('1');
        } else {
            output_error('密码错误');
        }
    }

    /**
     * 更换收货地址
     */
    public function change_addressOp() {
        $logic_buy = Logic('buy');
        if (empty($_POST['city_id'])) {
            $_POST['city_id'] = $_POST['area_id'];
        }
        
        $data = $logic_buy->changeAddr($_POST['freight_hash'], $_POST['city_id'], $_POST['area_id'], $this->member_info['member_id']);
        if(!empty($data) && $data['state'] == 'success' ) {
            output_data($data);
        } else {
            output_error('地址修改失败');
        }
    }

    /**
     * 实物订单支付(新接口)
     */
    public function payOp() {
        $pay_sn = $_POST['pay_sn'];
        if (!preg_match('/^\d{18}$/',$pay_sn)){
            output_error('该订单不存在');
        }

        //查询支付单信息
        $model_order= Model('order');
        $pay_info = $model_order->getOrderPayInfo(array('pay_sn'=>$pay_sn,'buyer_id'=>$this->member_info['member_id']),true);
        if(empty($pay_info)){
            output_error('该订单不存在');
        }
    
        //取子订单列表
        $condition = array();
        $condition['pay_sn'] = $pay_sn;
        $condition['order_state'] = array('in',array(ORDER_STATE_NEW,ORDER_STATE_PAY));
        $order_list = $model_order->getOrderList($condition,'','*','','',array(),true);
        if (empty($order_list)) {
            output_error('未找到需要支付的订单');
        }

        //定义输出数组
        $pay = array();
        //支付提示主信息
        //订单总支付金额(不包含货到付款)
        $pay['pay_amount'] = 0;
        //充值卡支付金额(之前支付中止，余额被锁定)
        $pay['payed_rcb_amount'] = 0;
        //预存款支付金额(之前支付中止，余额被锁定)
        $pay['payed_pd_amount'] = 0;
        //还需在线支付金额(之前支付中止，余额被锁定)
        $pay['pay_diff_amount'] = 0;
        //账户可用金额
        $pay['member_available_pd'] = 0;
        $pay['member_available_rcb'] = 0;

        $logic_order = Logic('order');

        //计算相关支付金额
        foreach ($order_list as $key => $order_info) {
            if (!in_array($order_info['payment_code'],array('offline','chain'))) {
                if ($order_info['order_state'] == ORDER_STATE_NEW) {
                    $pay['payed_rcb_amount'] += $order_info['rcb_amount'];
                    $pay['payed_pd_amount'] += $order_info['pd_amount'];
                    $pay['pay_diff_amount'] += $order_info['order_amount'] - $order_info['rcb_amount'] - $order_info['pd_amount'];
                }
            }
        }
        if ($order_info['chain_id'] && $order_info['payment_code'] == 'chain') {
            $order_list[0]['order_remind'] = '下单成功，请在'.CHAIN_ORDER_PAYPUT_DAY.'日内前往门店提货，逾期订单将自动取消。';
            $flag_chain = 1;
        }

        //如果线上线下支付金额都为0，转到支付成功页
        if (empty($pay['pay_diff_amount'])) {
            output_error('订单重复支付');
        }

        $payment_list = Model('mb_payment')->getMbPaymentOpenList();
        if(!empty($payment_list)) {
            foreach ($payment_list as $k => $value) {
                if ($value['payment_code'] == 'wxpay') {
                    unset($payment_list[$k]);
                    continue;
                }
                unset($payment_list[$k]['payment_id']);
                unset($payment_list[$k]['payment_config']);
                unset($payment_list[$k]['payment_state']);
                unset($payment_list[$k]['payment_state_text']);
            }
        }
            //显示预存款、支付密码、充值卡
            $pay['member_available_pd'] = $this->member_info['available_predeposit'];
            $pay['member_available_rcb'] = $this->member_info['available_rc_balance'];
            $pay['member_paypwd'] = $this->member_info['member_paypwd'] ? true : false;
        $pay['pay_sn'] = $pay_sn;
        $pay['payed_amount'] = ncPriceFormat($pay['payed_rcb_amount']+$pay['payed_pd_amount']);
        unset($pay['payed_pd_amount']);unset($pay['payed_rcb_amount']);
        $pay['pay_amount'] = ncPriceFormat($pay['pay_diff_amount']);
        unset($pay['pay_diff_amount']);
        $pay['member_available_pd'] = ncPriceFormat($pay['member_available_pd']);
        $pay['member_available_rcb'] = ncPriceFormat($pay['member_available_rcb']);
        $pay['payment_list'] = $payment_list ? array_values($payment_list) : array();
        output_data(array('pay_info'=>$pay));
    }

    /**
     *  添加充值订单
     */
    public function rechargeOp(){
        $pdr_amount = abs(floatval($_POST['order_amount']));
        if ($pdr_amount <= 0) {
            output_error('非法充值金额');
        }
        $model_pdr = Model('predeposit');
        $data = array();
        $data['pdr_sn'] = $pay_sn = $model_pdr->makeSn();
        $data['pdr_member_id'] = $this->member_info['member_id'];
        $data['pdr_member_name'] = $this->member_info['member_name'];
        $data['pdr_amount'] = $pdr_amount;
        $data['pdr_add_time'] = TIMESTAMP;
        $insert = $model_pdr->addPdRecharge($data);
        if (!$insert) {
            output_error('发起支付失败，请稍后再试');
        }
        $payment_list = Model('mb_payment')->getMbPaymentOpenList();
        if(!empty($payment_list)) {
            foreach ($payment_list as $k => $value) {
                if ($value['payment_code'] == 'wxpay') {
                    unset($payment_list[$k]);
                    continue;
                }
                unset($payment_list[$k]['payment_id']);
                unset($payment_list[$k]['payment_config']);
                unset($payment_list[$k]['payment_state']);
                unset($payment_list[$k]['payment_state_text']);
            }
        }
        $pay['pay_sn'] = $data['pdr_sn'];
        $pay['pay_amount'] = ncPriceFormat($_POST['order_amount']);
        $pay['payment_list'] = $payment_list ? array_values($payment_list) : array();
        output_data(array('pay_info'=>$pay));
    }

    /*
     * 线下扫码支付
     */
    public function offline_payOp() {
        //生成支付单信息
        $model_offline_order= Model('offline_order');
        $store_info = Model('store')->getStoreOnlineInfoByID($_POST['store_id']);
        if ($this->member_info['member_id'] == $store_info['member_id']) {
            output_error('不能给自己的店铺进行支付');
        }
        $member_info = $this->member_info;
        $settings = Model('setting')->getListSetting();
        //商圈店
        if($store_info['store_class']) {
            $fx_sq_hy = $settings['fx_sq_hy']; //消费者分销比例
            $fx_hy_level_one = $settings['fx_sq_hy_one']; //推荐人一级分销比例
            $fx_hy_level_two = $settings['fx_sq_hy_two']; //推荐人二级分销比例
            $fx_sq_sh_one = $settings['fx_sq_sh_one']; //推荐商圈商户一级分销比例
            $fx_sq_sh_two = $settings['fx_sq_sh_two']; //推荐商圈商户二级分销比例
        } else {
            $fx_hy_level_one = $settings['fx_hy_level_one'];  //一级分销比例
            $fx_hy_level_two = $settings['fx_hy_level_two']; //二级分销比例
            $fx_hy_brand = $settings['fx_hy_brand']; //品牌商分销比例
            $fx_hy_share = $settings['fx_hy_share']; //分享商分销比例
        }
        $fx_dl_city = $settings['fx_dl_city']; //市代分销比例
        $fx_dl_area = $settings['fx_dl_area']; //镇代分销比例
        $fx_dl_ty = $settings['fx_dl_ty']; //体验馆分销比例
        $fx_dl_ty_one = $settings['fx_dl_ty_one']; //体验馆一级分销比例

        $invite_one = 0;
        $invite_two = 0;

        $model_member = Model('member');
        $model_agent = Model('agent');
        if ($member_info['lev1']) {
            $invite_one = $fx_hy_level_one;
            $condition['member_id'] = $member_info['lev1'];
            if ($member_info['lev2']) {
                $invite_two = $fx_hy_level_two;
                $condition['member_id'] = ['in',$member_info['lev1'].','.$member_info['lev2']];
            }
            $inviters = $model_member->getMemberList($condition);
            if ($inviters) {
                foreach($inviters as $v) {
                    if ($member_info['lev1'] == $v['member_id']) {
                        //查询一级是否为体验馆
                        $agent_info = $model_agent->getAgentInfo(['member_id'=>$v['member_id']]);
                        if ($agent_info && $agent_info['type'] == 4) {
                            //体验馆专属一级分销比例
                            $invite_one = $fx_dl_ty_one;
                        }
                        if ($v['type']) {
                            $invite_one = $v['type'] == 1 ? $fx_hy_level_one + $fx_hy_brand : $fx_hy_level_one + $fx_hy_share;
                        }
                    }
                    if ($member_info['lev2'] && $member_info['lev2'] == $v['member_id']) {
                        if ($v['type']) {
                            $invite_two = $v['type'] == 1 ? $fx_hy_level_two + $fx_hy_brand : $fx_hy_level_two + $fx_hy_share;
                        }
                    }
                }
            }
        }



//---------------------------------------------------分销佣金处理start-----------------------------------------------------
        //商品总利润
        $total_goods_rates = $_POST['order_amount'] * $store_info['rates']/100;
        //会员各层级分销金额
        $rate['invite_rates'] = doubleval($total_goods_rates * $invite_one / 100);
        $rate['invite_rates_two'] = doubleval($total_goods_rates * $invite_two / 100);
        //代理分销金额
        $rate['city_rates'] = doubleval($total_goods_rates * $fx_dl_city / 100);
        $rate['area_rates'] = doubleval($total_goods_rates * $fx_dl_area / 100);
        $rate['ty_rates'] = doubleval($total_goods_rates * $fx_dl_ty / 100);
        //商圈独有分销金额
        if($store_info['store_class']) {
            //消费者返现金额
            $rate['member_rates'] = doubleval($total_goods_rates * $fx_sq_hy / 100);
            //推荐商圈商户一级分销金额
            if ($store_info['invite']) {
                $rate['sq_store_rates'] = doubleval($total_goods_rates * $fx_sq_sh_one / 100);
            }
            //推荐商圈商户二级分销金额
            if ($store_info['invite_two']) {
                $rate['sq_store_rates_two'] = doubleval($total_goods_rates * $fx_sq_sh_two / 100);
            }
        }
//------------------------------------------------分销佣金处理end----------------------------------------------------------

        $data = [
            'order_sn' => $this->makeOrderSn(),
            'buyer_id' => $this->member_info['member_id'],
            'buyer_name' => $this->member_info['member_name'],
            'store_id' => $_POST['store_id'],
            'store_name' => $store_info['store_name'],
            'payment_code' => "navgator",
            'order_amount' => $_POST['order_amount'],
            'add_time' => time(),
            'invite_rates' => $rate['invite_rates'] ? $rate['invite_rates'] : 0,
            'invite_rates_two' => $rate['invite_rates_two'] ? $rate['invite_rates_two'] : 0,
            'city_rates' => $rate['city_rates'] ? $rate['city_rates'] : 0,
            'area_rates' => $rate['area_rates'] ? $rate['area_rates'] : 0,
            'ty_rates' => $rate['ty_rates'] ? $rate['ty_rates'] : 0,
            'member_rates' => $rate['member_rates'] ? $rate['member_rates'] : 0,
            'sq_store_rates' => $rate['sq_store_rates'] ? $rate['sq_store_rates'] : 0,
            'sq_store_rates_two' => $rate['sq_store_rates_two'] ? $rate['sq_store_rates_two'] : 0,
        ];
        //线下现金支付
        if ($_POST['pay_type']) {
            $data['type'] = 1;
            $data['order_state'] = 20;
            $data['payment_time'] = time();
            $res = $model_offline_order->addOrder($data);
            if(!$res){
                output_error('支付失败，请稍后再试');
            }
            output_data(array('order_info'=>$data));
            exit;
        }else{
            $data['recive'] = 1;
        }
        //线上支付
        $res = $model_offline_order->addOrder($data);
        if(!$res){
            output_error('发起支付失败，请稍后再试');
        }
        //定义输出数组
        $pay = array();
        //支付提示主信息
        //订单总支付金额(不包含货到付款)
        $pay['pay_amount'] = 0;
        //充值卡支付金额(之前支付中止，余额被锁定)
        $pay['payed_rcb_amount'] = 0;
        //预存款支付金额(之前支付中止，余额被锁定)
        $pay['payed_pd_amount'] = 0;
        //还需在线支付金额(之前支付中止，余额被锁定)
        $pay['pay_diff_amount'] = 0;
        //账户可用金额
        $pay['member_available_pd'] = 0;
        $pay['member_available_rcb'] = 0;


        $payment_list = Model('mb_payment')->getMbPaymentOpenList();
        if(!empty($payment_list)) {
            foreach ($payment_list as $k => $value) {
                if ($value['payment_code'] == 'wxpay') {
                    unset($payment_list[$k]);
                    continue;
                }
                unset($payment_list[$k]['payment_id']);
                unset($payment_list[$k]['payment_config']);
                unset($payment_list[$k]['payment_state']);
                unset($payment_list[$k]['payment_state_text']);
            }
        }
        //显示预存款、支付密码、充值卡
        $pay['member_available_pd'] = $this->member_info['available_predeposit'];
        $pay['member_available_rcb'] = $this->member_info['available_rc_balance'];
        $pay['member_paypwd'] = $this->member_info['member_paypwd'] ? true : false;
        $pay['pay_sn'] = $data['order_sn'];
        $pay['payed_amount'] = 0;
        $pay['pay_amount'] = ncPriceFormat($_POST['order_amount']);
        $pay['member_available_pd'] = ncPriceFormat($pay['member_available_pd']);
        $pay['member_available_rcb'] = ncPriceFormat($pay['member_available_rcb']);
        $pay['payment_list'] = $payment_list ? array_values($payment_list) : array();
        output_data(array('pay_info'=>$pay));
    }

    /*
     * 线下扫码订单支付
     */
    public function offline_Order_payOp() {
        $pay_sn = $_POST['pay_sn'];
        if (!preg_match('/^\d{18}$/',$pay_sn)){
            output_error('该订单不存在');
        }

        //得到订单信息
        $model_offline_order= Model('offline_order');
        $offline_order_info = $model_offline_order->getOrderInfo(array('order_sn'=>$_POST['pay_sn']));
        $store_info = Model('store')->getStoreOnlineInfoByID($offline_order_info['store_id']);
        if ($this->member_info['member_id'] == $store_info['member_id']) {
            output_error('不能给自己的店铺进行支付');
        }

        //定义输出数组
        $pay = array();
        //支付提示主信息
        //订单总支付金额(不包含货到付款)
        $pay['pay_amount'] = 0;
        //充值卡支付金额(之前支付中止，余额被锁定)
        $pay['payed_rcb_amount'] = 0;
        //预存款支付金额(之前支付中止，余额被锁定)
        $pay['payed_pd_amount'] = 0;
        //还需在线支付金额(之前支付中止，余额被锁定)
        $pay['pay_diff_amount'] = 0;
        //账户可用金额
        $pay['member_available_pd'] = 0;
        $pay['member_available_rcb'] = 0;


        $payment_list = Model('mb_payment')->getMbPaymentOpenList();
        if(!empty($payment_list)) {
            foreach ($payment_list as $k => $value) {
                if ($value['payment_code'] == 'wxpay') {
                    unset($payment_list[$k]);
                    continue;
                }
                unset($payment_list[$k]['payment_id']);
                unset($payment_list[$k]['payment_config']);
                unset($payment_list[$k]['payment_state']);
                unset($payment_list[$k]['payment_state_text']);
            }
        }
        //显示预存款、支付密码、充值卡
        $pay['member_available_pd'] = $this->member_info['available_predeposit'];
        $pay['member_available_rcb'] = $this->member_info['available_rc_balance'];
        $pay['member_paypwd'] = $this->member_info['member_paypwd'] ? true : false;
        $pay['pay_sn'] = $offline_order_info['order_sn'];
        $pay['payed_amount'] = 0;
        $pay['pay_amount'] = ncPriceFormat($offline_order_info['order_amount']);
        $pay['member_available_pd'] = ncPriceFormat($pay['member_available_pd']);
        $pay['member_available_rcb'] = ncPriceFormat($pay['member_available_rcb']);
        $pay['payment_list'] = $payment_list ? array_values($payment_list) : array();
        output_data(array('pay_info'=>$pay));
    }


    /**
     * AJAX验证支付密码
     */
    public function check_pd_pwdOp(){
        if (empty($_POST['password'])) {
            output_error('支付密码格式不正确');
        }
        $buyer_info = Model('member')->getMemberInfoByID($this->member_info['member_id'],'member_paypwd');
        if ($buyer_info['member_paypwd'] != '') {
            if ($buyer_info['member_paypwd'] === md5($_POST['password'])) {
                output_data('1');
            }
        }
        output_error('支付密码验证失败');
    }

    /**
     * F码验证
     */
    public function check_fcodeOp() {
        $goods_id = intval($_POST['goods_id']);
        if ($goods_id <= 0) {
            output_error('商品ID格式不正确');
        }
        if ($_POST['fcode'] == '') {
            output_error('F码格式不正确');
        }
        $result = logic('buy')->checkFcode($goods_id, $_POST['fcode']);
        if ($result['state']) {
            output_data('1');
        } else {
            output_error('F码验证抢购');
        }
    }

    /**
     * 生成支付单编号(两位随机 + 从2000-01-01 00:00:00 到现在的秒数+微秒+会员ID%1000)，该值会传给第三方支付接口
     * 长度 =2位 + 10位 + 3位 + 3位  = 18位
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @return string
     */
    public function makeOrderSn($member_id) {
        return mt_rand(10,99)
        . sprintf('%010d',time() - 946656000)
        . sprintf('%03d', (float) microtime() * 1000)
        . sprintf('%03d', (int) $member_id % 1000);
    }
    /**
     * 获得积分购买数据
     * @param $cart
     */
    public function getPointProdInfo($cart){
        if(!is_array($cart)){
            $data = ['status'=>false,'msg'=>"购物车参数错误"];
            return $data;
        }
        $pointprod = Model('pointprod');
        $res = $pointprod->getPointProdInfo(array('pgoods_id'=>$cart[0]));
        if(!$res){
            $data = ['status'=>false,'msg'=>"商品信息错误"];
            return $data;
        }
        $data['status'] = true;
        $data['data']['pointprod_list'][0] = $res ;
        $data['data']['pointprod_list'][0]['quantity'] = $cart[1];
        $data['data']['pgoods_pointall'] = $data['data']['pointprod_list']['0']['pgoods_points']*$cart[1];
        return $data;
    }
}
